package org.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.atguigu.gmall.realtime.app.BaseApp;
import org.atguigu.gmall.realtime.bean.UserLoginBean;
import org.atguigu.gmall.realtime.common.Constant;
import org.atguigu.gmall.realtime.util.AtguiguUtil;
import org.atguigu.gmall.realtime.util.FlinkSinkUtil;

import java.time.Duration;

/**
 * Project:gmallRealTime
 * Package:org.atguigu.gmall.realtime.app.dws
 * Author: ZengHaiFeng
 * CreateTime:2023/5/4 17:03:15
 * Description: Todo
 * Version：1.0
 */
public class Dws_04_DwsUserUserLoginWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_04_DwsUserUserLoginWindow().init(
                40004,2,
                Constant.TOPIC_DWD_TRAFFIC_PAGE,
                "Dws_04_DwsUserUserLoginWindow");
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // filter user login log data
        SingleOutputStreamOperator<JSONObject> filterStream = filterUserLoginLog(ds);
        // parse to pojo
        SingleOutputStreamOperator<UserLoginBean> parseStream = ParseToPojo(filterStream);
        // window and aggregation
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(parseStream);

        // output to Clickhouse
        //resultStream.print();
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink(
                "dws_user_user_login_window",
                UserLoginBean.class));
    }

    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> parseStream) {
        return parseStream
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean value1, UserLoginBean value2) throws Exception {
                        value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                        value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                        return value1;
                    }
                },
                new AllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void apply(
                            TimeWindow window,
                            Iterable<UserLoginBean> values,
                            Collector<UserLoginBean> out) throws Exception {
                        UserLoginBean bean = values.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(window.getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(window.getEnd()));
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                }
                );
    }

    private SingleOutputStreamOperator<UserLoginBean> ParseToPojo(SingleOutputStreamOperator<JSONObject> filterStream) {
        return filterStream
                .keyBy(value -> value.getJSONObject("common").getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                    private ValueState<String> lastLoginDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastLoginDateState = getRuntimeContext()
                                .getState(new ValueStateDescriptor<>("lastLoginDagte",
                                        String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, UserLoginBean>.Context ctx, Collector<UserLoginBean> out) throws Exception {
                        Long ts = value.getLong("ts");
                        String today = AtguiguUtil.tsToDateTime(ts);
                        String lastLoginDate = lastLoginDateState.value();
                        Long uuCt = 0L;
                        Long backCt = 0L;
                        if (!today.equals(lastLoginDate)){
                            uuCt = 1L;
                            lastLoginDateState.update(today);
                            /*
                                Log in for the first time today and determine
                                whether it is a reflux user.
                             */
                            if (lastLoginDate != null){
                                Long lastLoginTs = AtguiguUtil.DateToTs(lastLoginDate);
                                if ((ts-lastLoginTs)/24/60/60/1000 >= 7){
                                    /*
                                        if the difference between the last login time and
                                        the current login time is more than seven days,
                                        the user is a reflux user.
                                     */
                                    backCt = 1L;
                                }
                            }
                        }
                        if (uuCt == 1){
                            out.collect(new UserLoginBean("","",backCt,uuCt,ts));
                        }
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> filterUserLoginLog(DataStreamSource<String> ds) {
        return ds
                // The data of ds is JSON, which is first parsed into JSONObject.
                .map(JSON::parseObject)
                // Add watermark first, easy to use later.
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((obj,ts)-> obj.getLong("ts"))
                        .withIdleness(Duration.ofSeconds(60)))
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) {
                        String uid = value.getJSONObject("common").getString("uid");
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");
                        /*
                            Two filtering conditions, one last page id is null
                             or the last page id is login and uid must not be null.
                         */
                        return (null == lastPageId || "login".equals(lastPageId)) && uid != null;
                    }
                });
    }
}
